package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * 卖票问题
 * 共享变量不是同一个，因此针对每一个步骤单独加锁即可
 */
@Slf4j(topic = "c.Test08_习题1_卖票")
public class Test08_习题1_卖票 {
    public static void main(String[] args) throws InterruptedException {
        //一个售票窗口，模拟多个人来买票
        TicketWindow window = new TicketWindow(1000);

        //创建2000个人
        List<Integer> amountList = new Vector<>();//每个线程卖出的票数放到集合，最后要求卖出去的票数
        List<Thread> threadList = new ArrayList<>();//为了等待所有的线程结束，所以保存线程
        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                int amount = window.sell(randomAmount());
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }

        //得等待所有线程运行结束
        for (Thread thread : threadList) {
            thread.join();
        }

        //统计卖出和剩余的票数
        log.debug("剩余票数：{}", window.getCount());
        log.debug("卖出去票数：{}", amountList.stream().mapToInt(i -> i).sum());
    }

    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~5n
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }
}

// 售票窗口
class TicketWindow {
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    // 获取余票数量
    public int getCount() {
        return count;
    }

    // 售票
    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}
